﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace PrestigeViewer
{
	public partial class main : Form
	{
		delegate void DelegateDisplayUserInfo(string name, string total, string prestige, string charm, string money, string uid);
		delegate void DelegateDisplayRate(string info, string tpid);

		Thread thread = null;
		string theuid = "";
		RegistryKey regkey = Registry.CurrentUser.CreateSubKey(@"Software\qiselang.cn\PrestigeViewer");

		[DllImport("uxtheme.dll", CharSet = CharSet.Unicode, EntryPoint = "SetWindowTheme")]
		private static extern Int32 SetWindowTheme(IntPtr hwnd, string subAppName, string subIdList);

		System.Timers.Timer timer = new System.Timers.Timer(100);
		bool autoscroll = true;

		public main()
		{
			InitializeComponent();
			SetWindowTheme(grid.Handle, "Explorer", null);

			this.MinimumSize = this.Size;

			uid.Text = regkey.GetValue("", "").ToString();
			uid.PreviewKeyDown += uid_PreviewKeyDown;

			menu.Opening += menu_Opening;
			open.Click += open_Click;
			copy.Click += copy_Click;

			this.FormClosing += main_FormClosing;

			timer.Elapsed += timer_Elapsed;
			timer.Start();

			nickname.Click += nickname_Click;
		}

		void nickname_Click(object sender, EventArgs e)
		{
			System.Diagnostics.Process.Start("http://bbs.meizu.cn/space-uid-" + nickname.Tag + ".html");
		}

		void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
		{
			try { BeginInvoke(new System.EventHandler(UpdateUI), new object[] { this, System.EventArgs.Empty }); } catch { }
		}
		private void UpdateUI(object o, System.EventArgs e)
		{
			if (grid.TopItem != null)
			{
				autoscroll = grid.Items[grid.Items.Count - 1].Bounds.Top < grid.Height - 24;
			}
		}

		void main_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (action.Text != "开始查找") action_Click(null, null);

			this.AllowTransparency = true;
			for (int i = 0; i < 10; i++)
			{
				this.Opacity -= .1;
				this.Top -= 2;
				Thread.Sleep(30);
			}
		}

		void uid_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
		{
			string text = uid.Text;
			if (e.KeyCode == Keys.Delete && e.Control && !"".Equals(text))
			{
				uid.Text = "";
				foreach (var name in regkey.GetValueNames())
				{
					if (text.Equals(regkey.GetValue(name).ToString()))
					{
						regkey.DeleteValue(name);
					}
				}
			}
		}

		void grid_ScrollVertical(object sender, System.Windows.Forms.ScrollEventArgs e)
		{
			//MessageBox.Show(e.Type == ScrollEventType.Last ? "1" : "2");
		}

		void copy_Click(object sender, EventArgs e)
		{
			List<string> links = new List<string>();
			for (int i = 0; i < grid.SelectedItems.Count; i++)
			{
				string link = grid.SelectedItems[i].Tag.ToString();
				if (!links.Contains(link)) links.Add(link);
			}
			Clipboard.SetText(string.Join("\n", links.ToArray()));
			label.Text = links.Count + "个帖子链接已复制";
			new Thread(new ThreadStart(delegate { Thread.Sleep(2000); label.Text = ""; })).Start();
		}

		void open_Click(object sender, EventArgs e)
		{
			System.Diagnostics.Process.Start(grid.SelectedItems[0].Tag.ToString());
		}

		void menu_Opening(object sender, System.ComponentModel.CancelEventArgs e)
		{
			int count = grid.SelectedItems.Count;
			e.Cancel = count == 0;
			open.Visible = count == 1;
		}

		private void uid_TextChanged(object sender, EventArgs e)
		{
			if (new Regex("^\\d+$").IsMatch(uid.Text))
			{
				action.Enabled = true;
				msg.Text = "点击“开始查找”";
			} else
			{
				action.Enabled = false;
				msg.Text = "输入正确的UID";
			}
		}

		void get_userinfo(object uid)
		{
			string s = Helper.GetSourceString("http://bbs.meizu.cn/space-uid-" + uid.ToString() + ".html");
			this.Invoke(new DelegateDisplayUserInfo(display_userinfo),
				Helper.SearchString(s, "<span class=\"t_right\" style=\"font-weight:bold;font-size:14px;float:left\"> (\\w+)</span>"),
				Helper.SearchString(s, "<span>帖子: (\\d+) </span>"),
				Helper.SearchString(s, "<span>威望: (\\d+) </span>"),
				Helper.SearchString(s, "<span>魅力: (\\d+) </span>"),
				Helper.SearchString(s, "<span>魅币: (\\d+) </span>"),
				uid.ToString());
		}
		void display_userinfo(string name, string total, string prestige, string charm, string money, string uid)
		{
			if ("".Equals(name))
			{
				nickname.Text = "";
				msg.Text = "没有查找到UID=" + uid + "的用户";
			} else
			{
				nickname.Text = name;
				nickname.Tag = uid;

				msg.Text = "  帖数：" + total + "   威望：" + prestige + "   魅力：" + charm + "   魅币：" + money;
				prog.Maximum = int.Parse(total);

				regkey.SetValue(name, theuid = uid);
				regkey.SetValue("", theuid);
				
				thread = new Thread(new ThreadStart(get_threadpages));
				thread.Start();
			}
		}

		int thepage = 1;

		void get_threadpages()
		{
			string s = Helper.GetSourceString("http://bbs.meizu.cn/space.php?item=all&uid=" + theuid + "&page=" + thepage);
			List<string> all = Helper.SearchStrings(s, "<a href=\"redirect\\.php\\?goto=findpost&amp;p(tid=\\d+&amp;pid=\\d+)\" target=\"_blank\"><span class=\"x_link\">\\[ 详情 \\]</span></a>");

			all.ForEach(get_ratings);

			Thread.Sleep(200);
			thepage++;
			get_threadpages();
		}

		void get_ratings(string tpid)
		{
			Thread.Sleep(200);
			string s = Helper.GetSourceString("http://bbs.meizu.cn/misc.php?action=viewratings&" + tpid.Replace("amp;", ""));
			try { this.Invoke(new DelegateDisplayRate(display_rating), s, tpid); } catch { }
		}
		void display_rating(string info, string tpid)
		{
			prog.Value++;
			progText.Text = "进度：" + prog.Value + " ";

			string tid = Helper.SearchString(tpid, "tid=(\\d+)");
			string pid = Helper.SearchString(tpid, "pid=(\\d+)");
			string title = Helper.SearchString(info, "<a href=\"viewthread.php\\?tid=\\d+\">(.*?)</a>");

			int index = info.IndexOf("<h1>查看评分记录</h1>");
			if (index > 0)
			{
				info = info.Substring(info.IndexOf("</thead>", index) + 8);
				info = info.Substring(0, info.IndexOf("</table>"));
				Regex regex = new Regex("<tr>\\s+<td>(.+?)\\s+<span.*?>(.+?)</span> </td>\\s+<td class=\"user\"><a href=\"space\\.php\\?uid=(.+?)\">(.+?)</a></td>\\s+<td class=\"time\">(.+?)</td>\\s+<td>(.*?)</td>\\s+</tr>", RegexOptions.Singleline);
				Match match = regex.Match(info);
				ListViewItem item;
				while (match.Success)
				{
					item = grid.Items.Add(new ListViewItem(new string[] {
						match.Groups[1] + " " + match.Groups[2],
						match.Groups[4].Value,
						match.Groups[5].Value,
						match.Groups[6].Value,
						title
					}) {
						Tag = "http://bbs.meizu.cn/redirect.php?goto=findpost&ptid=" + tid + "&pid=" + pid
					});

					if (match.Groups[2].Value.TrimStart().StartsWith("-"))
					{
						item.ForeColor = Color.Red;
						Helper.FlashWindow(this.Handle);
					}

					if (autoscroll) item.EnsureVisible();

					match = match.NextMatch();
				}
			}
		}

		private void action_Click(object sender, EventArgs e)
		{
			if (uid.Enabled)
			{
				nickname.Text = "";
				msg.Text = "正在查找用户...";
				grid.Items.Clear();
				thread = new Thread(new ParameterizedThreadStart(get_userinfo));
				thread.Start(uid.Text);

				uid.Enabled = false;
				action.Text = "停止查找";
				thepage = 1;
				prog.Value = 0;
				progText.Text = "";
			} else
			{
				thread.Abort();

				uid.Enabled = true;
				action.Text = "开始查找";
			}
		}

		private void users_Opening(object sender, System.ComponentModel.CancelEventArgs e)
		{
			users.Items.Clear();

			string[] names = regkey.GetValueNames();
			if (names.Length == 0)
			{
				e.Cancel = true;
			} else
			{
				foreach (var name in names)
				{
					if (name.Length == 0) continue;

					users.Items.Add(name, null, delegate
					{
						uid.Text = regkey.GetValue(name).ToString();
						uid.SelectAll();
						uid.Focus();
					});
				}
			}
		}
	}
}
